﻿using System;
using System.Collections.Generic;
using System.Management.Automation;
using Sitecore.Collections;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Serialization;
using Sitecore.Globalization;
using Sitecore.Publishing;
using Sitecore.Publishing.Pipelines.PublishItem;

namespace Cognifide.PowerShell.Shell.Commands
{
    [Cmdlet("Deserialize", "Item", SupportsShouldProcess = true, DefaultParameterSetName = "Item")]
    public class DeserializeItemCommand : BaseCommand
    {

        [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        public Database Database { get; set; }

        public Item Item { get; set; }
        
        [Parameter]
        public string Path { get; set; }

        [Parameter]
        public SwitchParameter Recurse { get; set; }

        [Parameter]
        public string Root { get; set; }

        [Parameter]
        public SwitchParameter UseNewId { get; set; }

        [Parameter]
        protected SwitchParameter DisableEvents { get; set; }

        protected override void ProcessRecord()
        {
            Deserialize(Path, this.CurrentProviderLocation("CmsItemProvider"));
        }

        public void Deserialize(string path, PathInfo currentPathInfo)
        {
            var options = new LoadOptions();
            options.Database = Database;
            options.Root = Root;
            options.UseNewID = UseNewId.IsPresent;
            options.DisableEvents = DisableEvents.IsPresent;

            if(Recurse.IsPresent)
            {
                Manager.LoadTree(path,options);
            }
            else
            {
                Manager.LoadItem(path, options);
            }
        }

    }
}

